//
//  ProfileController.swift
//  MoyoungMy
//
//  Created by 易先生 on 2022/8/11.
//

import UIKit
import MYModule
import RxSwift
import RxCocoa
import RxViewController
import HealthKit



class ProfileController: ViewController {
    
    static let lanchedDefaultKey = "lanchedDefaultKey"
    
    /// 判断是否首次启动
    static var lanched: Bool {
        
        let isFirst = UserDefaults.standard.bool(forKey: lanchedDefaultKey)
        return isFirst
        
    }

	public var isSetProfile: Bool = false

	private lazy var viewModel = ProfileViewModel()
    
    init() {
        super.init(nibName: nil, bundle: nil)
        
        self.modalTransitionStyle = .crossDissolve
        self.modalPresentationStyle = .fullScreen     
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
	override func viewDidLoad() {
		super.viewDidLoad()
	}
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        UserDefaults.standard.set(true, forKey: Self.lanchedDefaultKey)
        
        setFireBaseUserProperty()
        
    }
    
    
    /// 设置FireBase用户属性
    func setFireBaseUserProperty() {
        
        let items = viewModel.items.value
        items.forEach {
            var userPropertyType: FireBaseUserProperty.KeyType?
            switch $0.type {
                
            case .sex:
                userPropertyType = .user_gender
                break
            case .height:
                userPropertyType = .user_height
                break
            case .weight:
                userPropertyType = .user_weight
                break
            case .birth:
                userPropertyType = .user_age
                break
            case .steplength:
                userPropertyType = .user_step_size
                break
            default:
                break
            }
            
            guard let userPropertyType = userPropertyType else {
                return
            }
            var value = $0.value.value
            if userPropertyType == .user_age {
                value = "\(UserCacheManagement.userInfo().age)"
            }
            guard let value = value else {
                return
            }
            
            let userPropertyModel = FireBaseUserProperty(type: userPropertyType, value: value)
            FireBaseManager.shared.setUserProperty(userProperty: userPropertyModel)
        }
        
    }
    
	override func makeUI() {
		super.makeUI()
        
        self.navigation.bar.backgroundColor = UIColor.darkBackground
        
        view.backgroundColor =  UIColor.darkBackground
		view.addSubview(titleView)
		view.addSubview(tableView)

		titleView.snp.makeConstraints { make in
			make.top.equalTo(topLayoutGuide.snp.bottom)
			make.leading.equalToSuperview()
			make.trailing.equalToSuperview()
		}

		tableView.snp.makeConstraints { make in
            make.top.equalTo(titleView.snp.bottom)
			make.leading.trailing.bottom.equalToSuperview()
		}

		if isSetProfile {
			viewModel.setDefaultProfile()
			navigation.item.leftBarButtonItem = leftBarButtonItem
			view.addSubview(saveButton)
            
			saveButton.snp.makeConstraints { make in
				make.bottom.equalToSuperview().offset(-50)
                make.leading.equalToSuperview().offset(50)
				make.trailing.equalToSuperview().offset(-50)
                make.height.equalTo(50)
			}
		}

	}
    

	override func bindViewModel() {
        
        viewModel.items.bind(to: tableView.rx.items(cellIdentifier: ProfileCell.reuseIdentifier, cellType: ProfileCell.self)){row, item, cell in
            cell.bind(to: item)
        }.disposed(by: rx.disposeBag)

		tableView.rx.itemSelected.subscribe(onNext: { [weak self] indexPath in
			guard let self = self else { return }
			let item = self.viewModel.items.value[indexPath.row]
            switch item.type {
			case .sex:
				self.pushPickController(type: .sex, cellModel: item)
			case .height:
				self.pushPickController(type: .height, cellModel: item)
			case .weight:
				self.pushPickController(type: .weight, cellModel: item)
			case .birth:
				self.pushPickController(type: .birth, cellModel: item)
            case .steplength:
                self.pushPickController(type: .steplength, cellModel: item)
            default:
                break
			}
		}).disposed(by: rx.disposeBag)

		leftBarButtonItem.rx.tap.subscribe { [weak self] _ in
			guard let self = self else { return }
			self.dismiss(animated: true)
		}.disposed(by: rx.disposeBag)

		saveButton.rx.tap.subscribe { [weak self] _ in
			guard let self = self else { return }
            
			self.dismiss(animated: true)
            
		}.disposed(by: rx.disposeBag)
	}

	private func pushPickController(type: ProfileType, cellModel: ProfileCellViewModel) {
        let vc = ProfilePopController(showType: type)
		vc.itemValueChange.subscribe { [weak self] _ in
			guard let self = self else { return }
			self.viewModel.getItems()
		}.disposed(by: rx.disposeBag)
		self.present(vc, animated: true)
	}
    
	private lazy var tableView: TableView = {
		let tableView = TableView(frame: .zero, style: .plain)
		tableView.separatorColor = UIColor.assist_D0D0D0
		tableView.backgroundColor = .clear
		tableView.separatorStyle = .none
        tableView.rowHeight = 75
		tableView.register(ProfileCell.self, forCellReuseIdentifier: ProfileCell.reuseIdentifier)
		return tableView
	}()

	private lazy var titleView: TopTitleView = {
		let titleView = TopTitleView()
		titleView.configTitle(title: "info_setting_title".language)
		return titleView
	}()

	private lazy var saveButton: Button = {
		let saveButton = Button()
        saveButton.setTitle("dialog_finished".language, for: .normal)
        saveButton.setTitleColor(UIColor.assist_FFFFFF, for: .normal)
        saveButton.titleLabel?.font = Fonts.boldSystemFont(ofSize: 18)
        saveButton.backgroundColor = UIColor.theme
        saveButton.layer.cornerRadius = 25
		return saveButton
	}()

	private lazy var leftBarButtonItem: UIBarButtonItem = {
		let leftBarButtonItem = UIBarButtonItem()
		leftBarButtonItem.image = UIImage(named: "ic_close_n")
		return leftBarButtonItem
	}()

}
